﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class TLXuatKho : System.Web.UI.Page
{
    SqlParameter[] p;
    clsXuLy ex = new clsXuLy();
    string frmName = "frmXuatKho";
    static int f_SuDung = 0, f_Them = 0, f_Sua = 0, f_Xoa = 0, f_XemTatCa = 0, f_InBaoCao = 0;
    public string Header = System.Configuration.ConfigurationSettings.AppSettings["Header"].ToString();
    static DataTable dt;
    static int PageNumber = 6;
    static int CurrentPage = 1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Convert.ToString(Session["user"])))
            gstGetMess("Hết phiên làm việc, vui lòng đăng nhập để tiếp tục", "Default.aspx");
        else
        {
            if (!IsPostBack)
            {
                string idnguoidung = Session["IDUser"].ToString();
                string sql = "select SuDung,Them,Sua,Xoa,InBaoCao,XemTatCa from XDAPhanQuyen where IDnguoidung='" + idnguoidung + "' and tag='" + frmName + "'";
                DataTable dt2 = ex.GetData_Text(sql);
                if (dt2.Rows.Count > 0)
                {
                    f_SuDung = int.Parse(dt2.Rows[0]["SuDung"].ToString());
                    f_Them = int.Parse(dt2.Rows[0]["Them"].ToString());
                    f_Sua = int.Parse(dt2.Rows[0]["Sua"].ToString());
                    f_Xoa = int.Parse(dt2.Rows[0]["Xoa"].ToString());
                    f_InBaoCao = int.Parse(dt2.Rows[0]["InBaoCao"].ToString());
                    f_XemTatCa = int.Parse(dt2.Rows[0]["XemTatCa"].ToString());
                }
                if (f_SuDung.Equals(1))
                {
                    CurrentPage = 1;
                    btnCancel_Click(sender, e);
                    Title = "Quản lý xuất kho | " + Header;
                    LoadNCC_TimKiem();
                    for (int i = 1; i <= 12; i++)
                    {
                        dlThang.Items.Add(new ListItem("Tháng " + i.ToString(), i.ToString()));
                    }
                    dlThang.Items.Insert(0, new ListItem("Theo thời gian", ""));
                    dlThang.SelectedIndex = 0;

                    int year1 = DateTime.Now.Year - 3;
                    int year2 = DateTime.Now.Year;
                    for (int i = year2; i >= year1; i--)
                    {
                        dlNam.Items.Add(new ListItem("Năm " + i.ToString(), i.ToString()));
                    }
                    dlNam.SelectedValue = year2.ToString();

                    txtTuNgay.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    txtDenNgay.Text = DateTime.Now.ToString("dd/MM/yyyy");
                    dlNam.Visible = false;
                }
                else
                    gstGetMess("Bạn không có quyền xem trang này", "Home.aspx");

            }
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        FirstGridViewRow();
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@PageNumber", 1);
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@RowspPage", PageNumber);
        p[1].SqlDbType = SqlDbType.Int;
        dt = ex.GetData("sp_xdaxuatkho_List", p);
        GV.DataSource = dt;
        GV.DataBind();

    }


    private void gstGetMess(string gstMess, string gstLink)
    {
        if (gstLink == "")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "')", true);
        else
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "');window.location.href='" + gstLink + "'", true);

    }


    void LoadNCC_TimKiem()
    {
        dropNhanVien.Items.Clear();
        dropNhanVien.DataSource = ex.GetData("sp_XuatKho_ListLoaiVatLieuDrop");
        dropNhanVien.DataBind();
        dropNhanVien.Items.Insert(0, new ListItem("--Chọn loại vật liệu--", ""));
        dropNhanVien.SelectedIndex = 0;
    }



    string ConvertDecimal(double s)
    {
        string q = "";
        if (s.ToString().Contains("."))
        {
            double x = double.Parse(s.ToString().Substring(0, s.ToString().IndexOf('.')));
            q = (x != 0 && x > 999) ? string.Format("{0:0,0}", x) : x.ToString();
            q += s.ToString().Substring(s.ToString().IndexOf('.'));
        }
        else
            q = (s != 0 && s > 999) ? string.Format("{0:0,0}", s) : s.ToString();
        return q;
    }
    private void AddNewRow()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox txtngaythang = (TextBox)GV1.Rows[rowIndex].Cells[1].FindControl("txtngaythang");
                    DropDownList dlnhomvatlieu = (DropDownList)GV1.Rows[rowIndex].Cells[2].FindControl("drnhomvatlieu");
                    DropDownList dlloaivatlieu = (DropDownList)GV1.Rows[rowIndex].Cells[3].FindControl("drloaivatlieu");
                    DropDownList dldonvi = (DropDownList)GV1.Rows[rowIndex].Cells[4].FindControl("dldonvi");
                    TextBox txtsoluong = (TextBox)GV1.Rows[rowIndex].Cells[5].FindControl("txtsoluong");
                    TextBox txtdongia = (TextBox)GV1.Rows[rowIndex].Cells[6].FindControl("txtdongia");
                    TextBox txtthanhtien = (TextBox)GV1.Rows[rowIndex].Cells[7].FindControl("txtthanhtien");
                    DropDownList dldoituong = (DropDownList)GV1.Rows[rowIndex].Cells[8].FindControl("dldoituong");
                    DropDownList dlmathietbi = (DropDownList)GV1.Rows[rowIndex].Cells[9].FindControl("drmathietbi");
                    CheckBox ckVAT = (CheckBox)GV1.Rows[rowIndex].Cells[10].FindControl("ckVAT");
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["NgayThang"] = txtngaythang.Text.Trim();
                    dtCurrentTable.Rows[i - 1]["DonVi"] = dldonvi.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["SoLuong"] = txtsoluong.Text.Trim();
                    dtCurrentTable.Rows[i - 1]["DonGia"] = txtdongia.Text.Trim();
                    dtCurrentTable.Rows[i - 1]["ThanhTien"] = txtthanhtien.Text.Trim();
                    dtCurrentTable.Rows[i - 1]["CoVAT"] = ckVAT.Checked.ToString();
                    dtCurrentTable.Rows[i - 1]["DoiTuong"] = dldoituong.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["NhomVatLieu"] = dlnhomvatlieu.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["LoaiVatLieu"] = dlloaivatlieu.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["MaThietBi"] = dlmathietbi.SelectedValue;
                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                GV1.DataSource = dtCurrentTable;
                GV1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();

    }
    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox txtngaythang = (TextBox)GV1.Rows[rowIndex].Cells[1].FindControl("txtngaythang");
                    DropDownList dlnhomvatlieu = (DropDownList)GV1.Rows[rowIndex].Cells[2].FindControl("drnhomvatlieu");
                    DropDownList dlloaivatlieu = (DropDownList)GV1.Rows[rowIndex].Cells[3].FindControl("drloaivatlieu");
                    DropDownList dldonvi = (DropDownList)GV1.Rows[rowIndex].Cells[4].FindControl("dldonvi");
                    TextBox txtsoluong = (TextBox)GV1.Rows[rowIndex].Cells[5].FindControl("txtsoluong");
                    TextBox txtdongia = (TextBox)GV1.Rows[rowIndex].Cells[6].FindControl("txtdongia");
                    TextBox txtthanhtien = (TextBox)GV1.Rows[rowIndex].Cells[7].FindControl("txtthanhtien");
                    DropDownList dldoituong = (DropDownList)GV1.Rows[rowIndex].Cells[8].FindControl("dldoituong");
                    DropDownList dlmathietbi = (DropDownList)GV1.Rows[rowIndex].Cells[9].FindControl("drmathietbi");
                    CheckBox ckVAT = (CheckBox)GV1.Rows[rowIndex].Cells[10].FindControl("ckVAT");

                    GV1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    txtngaythang.Focus();
                    txtngaythang.Text = dt.Rows[i]["NgayThang"].ToString();                 
                    dlnhomvatlieu.SelectedValue = dt.Rows[i]["NhomVatLieu"].ToString();
                    dlloaivatlieu.SelectedValue = dt.Rows[i]["LoaiVatLieu"].ToString();
                    dldonvi.SelectedValue = dt.Rows[i]["DonVi"].ToString();
                    txtsoluong.Text = dt.Rows[i]["SoLuong"].ToString();
                    txtdongia.Text = dt.Rows[i]["DonGia"].ToString();
                    dlmathietbi.SelectedValue = dt.Rows[i]["MaThietBi"].ToString();
                    txtthanhtien.Text = dt.Rows[i]["ThanhTien"].ToString();
                    dldoituong.SelectedValue = dt.Rows[i]["DoiTuong"].ToString();
                    string vat = dt.Rows[i]["CoVAT"].ToString();

                    ckVAT.Checked = vat.Equals("") ? false : bool.Parse(dt.Rows[i]["CoVAT"].ToString());

                    rowIndex++;
                }
            }
        }
    }
    private void FirstGridViewRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("NgayThang", typeof(string)));
        dt.Columns.Add(new DataColumn("DonVi", typeof(string)));
        dt.Columns.Add(new DataColumn("SoLuong", typeof(string)));
        dt.Columns.Add(new DataColumn("DonGia", typeof(string)));
        dt.Columns.Add(new DataColumn("ThanhTien", typeof(string)));
        dt.Columns.Add(new DataColumn("CoVAT", typeof(bool)));
        dt.Columns.Add(new DataColumn("NhomVatLieu", typeof(string)));
        dt.Columns.Add(new DataColumn("MaThietBi", typeof(string)));
        dt.Columns.Add(new DataColumn("LoaiVatLieu", typeof(string)));
        dt.Columns.Add(new DataColumn("DoiTuong", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["NgayThang"] = string.Empty;
        dr["LoaiVatLieu"] = string.Empty;
        dr["NhomVatLieu"] = string.Empty;
        dr["MaThietBi"] = string.Empty;
        dr["DonVi"] = string.Empty;
        dr["SoLuong"] = string.Empty;
        dr["DonGia"] = string.Empty;
        dr["ThanhTien"] = string.Empty;
        dr["DoiTuong"] = string.Empty;
        dr["CoVAT"] = false;
        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;


        GV1.DataSource = dt;
        GV1.DataBind();
    }
    protected void gv_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;
                GV1.DataSource = dt;
                GV1.DataBind();

                for (int i = 0; i < GV1.Rows.Count - 1; i++)
                {
                    GV1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetPreviousData();
            }
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }

    protected void btnSave_Click1(object sender, EventArgs e)
    {
        if (f_Them.Equals(1))
        {
            try
            {
                for (int i = 0; i < GV1.Rows.Count; i++)
                {
                    TextBox txtngaythang = (TextBox)GV1.Rows[i].Cells[1].FindControl("txtngaythang");
                    DropDownList dlnhomvatlieu = (DropDownList)GV1.Rows[i].Cells[2].FindControl("drnhomvatlieu");
                    DropDownList dlloaivatlieu = (DropDownList)GV1.Rows[i].Cells[3].FindControl("drloaivatlieu");
                    DropDownList dldonvi = (DropDownList)GV1.Rows[i].Cells[4].FindControl("dldonvi");
                    TextBox txtsoluong = (TextBox)GV1.Rows[i].Cells[5].FindControl("txtsoluong");
                    TextBox txtdongia = (TextBox)GV1.Rows[i].Cells[6].FindControl("txtdongia");
                    TextBox txtthanhtien = (TextBox)GV1.Rows[i].Cells[7].FindControl("txtthanhtien");
                    DropDownList dldoituong = (DropDownList)GV1.Rows[i].Cells[8].FindControl("dldoituong");
                    DropDownList dlmathietbi = (DropDownList)GV1.Rows[i].Cells[9].FindControl("drmathietbi");
                    CheckBox ckVAT = (CheckBox)GV1.Rows[i].Cells[10].FindControl("ckVAT");
                    # region insert nhapkho
                    p = new SqlParameter[12];
                    p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                    p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[1] = new SqlParameter("@NgayThang", ex.GetNgayThang(txtngaythang.Text.Trim()));
                    p[1].SqlDbType = SqlDbType.SmallDateTime;
                    p[2] = new SqlParameter("@NhomVatLieu", ex.GetGuid(dlnhomvatlieu.SelectedValue));
                    p[2].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[3] = new SqlParameter("@LoaiVatLieu", ex.GetGuid(dlloaivatlieu.SelectedValue));
                    p[3].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[4] = new SqlParameter("@DonVi", ex.GetGuid(dldonvi.SelectedValue));
                    p[4].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[5] = new SqlParameter("@SoLuong", double.Parse(txtsoluong.Text.Trim().Equals("") ? "0" : txtsoluong.Text.Trim()));
                    p[5].SqlDbType = SqlDbType.Float;
                    p[6] = new SqlParameter("@DonGia", double.Parse(txtdongia.Text.Trim().Equals("") ? "0" : txtdongia.Text.Trim()));
                    p[6].SqlDbType = SqlDbType.Float;
                    p[7] = new SqlParameter("@ThanhTien", double.Parse(txtthanhtien.Text.Trim().Equals("") ? "0" : txtthanhtien.Text.Trim()));
                    p[7].SqlDbType = SqlDbType.Float;
                    p[8] = new SqlParameter("@DoiTuong", ex.GetGuid(dldoituong.SelectedValue));
                    p[8].SqlDbType = SqlDbType.UniqueIdentifier;
                    p[9] = new SqlParameter("@MaThietBi", dlmathietbi.SelectedValue);
                    p[9].SqlDbType = SqlDbType.NVarChar;
                    p[10] = new SqlParameter("@CoVAT", ckVAT.Checked ? 1 : 2);
                    p[10].SqlDbType = SqlDbType.Int;
                    p[11] = new SqlParameter("@Del", 1);
                    p[11].SqlDbType = SqlDbType.Int;         
                    ex.ExecuteNonQuerry("sp_xdaxuatkho_Add", p);
                    #endregion
                }

                btnCancel_Click(sender, e);
                gstGetMess("Lưu thành công", "");
            }
            catch (Exception ax)
            {
                gstGetMess("Có lỗi trong quá trình lưu, xem trong file log", "");
                ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tThiết lập thanh toán tiền mặt\t" + ax.Message);
            }
        }
        else
            gstGetMess("Bạn không có quyền thêm dữ liệu trên trang này", "");
    }

    protected void btnFirst_Click(object sender, EventArgs e)
    {
        CurrentPage = 1;
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@PageNumber", CurrentPage);
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@RowspPage", PageNumber);
        p[1].SqlDbType = SqlDbType.Int;

        GV.DataSource = ex.GetData("sp_xdaxuatkho_List", p);
        GV.DataBind();

        btnPre.Enabled = false;
        btnNext.Enabled = true;
        btnFirst.Enabled = false;
    }
    protected void btnPre_Click(object sender, EventArgs e)
    {
        if (CurrentPage > 1)
        {
            CurrentPage--;
            btnPre.Enabled = true;
            btnNext.Enabled = true;
            btnFirst.Enabled = true;

            p = new SqlParameter[2];
            p[0] = new SqlParameter("@PageNumber", CurrentPage);
            p[0].SqlDbType = SqlDbType.Int;
            p[1] = new SqlParameter("@RowspPage", PageNumber);
            p[1].SqlDbType = SqlDbType.Int;

            GV.DataSource = ex.GetData("sp_xdaxuatkho_List", p);
            GV.DataBind();

        }
        else
        {
            btnFirst.Enabled = false;
            btnPre.Enabled = false;
            btnNext.Enabled = true;
        }
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        CurrentPage++;
        p = new SqlParameter[2];
        p[0] = new SqlParameter("@PageNumber", CurrentPage);
        p[0].SqlDbType = SqlDbType.Int;
        p[1] = new SqlParameter("@RowspPage", PageNumber);
        p[1].SqlDbType = SqlDbType.Int;

        GV.DataSource = ex.GetData("sp_xdaxuatkho_List", p);
        GV.DataBind();

        if (GV.Rows.Count.Equals(0))
        {
            btnPre.Enabled = true;
            btnNext.Enabled = false;
        }
        else
        {
            btnPre.Enabled = true;
            btnNext.Enabled = true;
        }
        btnFirst.Enabled = true;
    }


    protected void dlThang_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (dlThang.SelectedIndex.Equals(0))
        {
            txtTuNgay.Visible = true;
            txtDenNgay.Visible = true;
            dlNam.Visible = false;
        }
        else
        {
            txtTuNgay.Visible = false;
            txtDenNgay.Visible = false;
            dlNam.Visible = true;
        }
    }
    protected void btnXem_Click(object sender, EventArgs e)
    {
        getDate();
        if (dropNhanVien.SelectedIndex == 0)
        {
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
            p[0].SqlDbType = SqlDbType.SmallDateTime;
            p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
            p[1].SqlDbType = SqlDbType.SmallDateTime;
            GV.DataSource = ex.GetData("sp_xdaxuatkho_ListTheoThoiGian", p);
            GV.DataBind();
            p = new SqlParameter[2];
            p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
            p[0].SqlDbType = SqlDbType.SmallDateTime;
            p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
            p[1].SqlDbType = SqlDbType.SmallDateTime;
            GridView1.DataSource = ex.GetData("sp_xdaxuatkho_ListTheoThoiGian", p);
            GridView1.DataBind();
        }
        else
        {
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
            p[0].SqlDbType = SqlDbType.SmallDateTime;
            p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
            p[1].SqlDbType = SqlDbType.SmallDateTime;
            p[2] = new SqlParameter("@LoaiVatLieu", ex.GetGuid(dropNhanVien.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            GV.DataSource = ex.GetData("sp_xdaxuatkho_ListTheoThoiGian_LoaiVatLieu", p);
            GV.DataBind();
            p = new SqlParameter[3];
            p[0] = new SqlParameter("@TuNgay", ex.GetNgayThang(hdTuNgay.Value));
            p[0].SqlDbType = SqlDbType.SmallDateTime;
            p[1] = new SqlParameter("@DenNgay", ex.GetNgayThang(hdDenNgay.Value));
            p[1].SqlDbType = SqlDbType.SmallDateTime;
            p[2] = new SqlParameter("@LoaiVatLieu", ex.GetGuid(dropNhanVien.SelectedValue));
            p[2].SqlDbType = SqlDbType.UniqueIdentifier;
            GridView1.DataSource = ex.GetData("sp_xdaxuatkho_ListTheoThoiGian_LoaiVatLieu", p);
            GridView1.DataBind();

        }
        btnFirst.Visible = false;
        btnPre.Visible = false; btnNext.Visible = false;

    }
    public void getDate()
    {
        if (dlThang.SelectedIndex.Equals(0))
        {
            hdTuNgay.Value = txtTuNgay.Text;
            hdDenNgay.Value = txtDenNgay.Text;
        }
        else
        {
            txtTuNgay.Text = "1/" + dlThang.SelectedValue + "/" + dlNam.SelectedValue;
            txtDenNgay.Text = GetLastDayOfMonth(int.Parse(dlThang.SelectedValue)).ToString("dd/MM/yyyy");
            hdTuNgay.Value = txtTuNgay.Text;
            hdDenNgay.Value = txtDenNgay.Text;
        }
    }
    public DateTime GetLastDayOfMonth(int iMonth)
    {
        DateTime dtResult = new DateTime(int.Parse(dlNam.SelectedValue), iMonth, 1);
        dtResult = dtResult.AddMonths(1);
        dtResult = dtResult.AddDays(-(dtResult.Day));
        return dtResult;
    }

    protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string ID = e.CommandArgument.ToString();
        hdID.Value = ID;
        Guid gID = new Guid(ID);
        p = new SqlParameter[1];


        if (e.CommandName.Equals("Del"))
        {
            p[0] = new SqlParameter("@IDs", gID);
            p[0].SqlDbType = SqlDbType.UniqueIdentifier;
            ex.ExecuteNonQuerry("sp_xdaxuatkho_Del", p);


            gstGetMess("Xóa thành công", "");
            btnCancel_Click(sender, e);
        }
    }



}